<?php
namespace app\system\controller;

use app\common\model\AreaModel;
use think\Request;

class AreaController extends BaseController
{

    private $areaModel;
    private $areaCache;

    /**
     * 初始化
     * AreaController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->areaModel = new AreaModel();
        $this->areaCache = cache('area');
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $pid        = $this->request->param('pid/d', 0);
        $map['pid'] = $pid;
        $area       = $this->areaModel->where($map)->order('area_sort')->select();
        $this->assign('area', $area);
        return $this->fetch();
    }

    /**
     * 添加区域
     */
    public function add()
    {
        try{
            $data   = $this->request->param();
            $result = $this->validate($data, [
                'area_name|区域名称' => 'require',
            ]);
            if (true !== $result) {
                exception($result,40001);
            }
            $this->areaModel->addData($data);
            $this->updateCache();
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('添加成功！');
    }

    /**
     * 级联删除区域
     */
    public function del()
    {
        try{
            $area = $this->areaModel->order('area_sort')->select();
            $id       = $this->request->param('id/d');
            $ids      = [$id];
            $children = \org\util\TreeUtil::channelList($area, $id);
            foreach ($children as $v) {
                $ids[] = $v['id'];
            }
            $this->areaModel->destroy($ids);
            $this->updateCache();
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }

    /**
     * 更新排序
     */
    public function upOrder()
    {
        try{
            $sort = $this->request->param('sort/a');
            if (!empty($sort)) {
                $dataList=[];
                foreach ($sort as $k => $v) {
                    $dataList[] = ['id' => (int)$k, 'area_sort' => (int)$v];
                }
                $this->areaModel->saveAll($dataList);
            } else {
                exception('参数错误！',40001);
            }
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('排序成功');
    }

    public function createjs()
    {
        $this->areaModel->createJs();
        $this->areaModel->buildCityPicker();
        $this->success('同步更新成功！');
    }

    public function updateCache()
    {
        $this->areaModel->updateCache();
        $this->success('操作成功！', url('index'));
    }

}
